import { checkIn, getDailyDataByDate } from '@/api/daily';
import { ResultCodeEnum } from '@/enums';
import {
  addDate,
  formatDate,
  formatTimestamp,
  getStartOrEndTimeStamp,
  isEqualDate,
  today
} from '@/utils/date';
import type { Dayjs } from 'dayjs';
import { useMessage, useToast } from 'wot-design-uni';
import type { MessageResult } from 'wot-design-uni/components/wd-message-box/types';
import type {
  CalendarDayItem,
  CalendarFormatter
} from 'wot-design-uni/components/wd-calendar-view/types';
import { useFetchAllSheetData } from '../log';

export const useDailyCheck = () => {
  const { getData, weekDateList, dataList } = useFetchAllSheetData();
  const showCalendar = ref(true);

  const formatter: CalendarFormatter = (day: CalendarDayItem) => {
    console.log('打印***day', day, dataList.value);
    dataList.value.forEach((item) => {
      if (isEqualDate(day.date, item.date, 'day')) {
        day.bottomInfo = item.percent.toString();
      }
    });

    return day;
  };

  const radioList = [
    { label: '20%', value: 20 },
    { label: '40%', value: 40 },
    { label: '60%', value: 60 },
    { label: '80%', value: 80 },
    { label: '100%', value: 100 },
    { label: '请假', value: 0 }
  ];

  const number = ref();
  type TModel = {
    date: number;
    value: string;
  };
  const model = reactive<TModel>({
    date: 0, // 默认获取前一天
    value: ''
  });

  console.log('打印***weekDateList', weekDateList);
  const initDate = () => {
    if (weekDateList.includes(today)) {
      if (today === weekDateList[0]) {
        model.date = formatTimestamp(today);
      } else {
        model.date = addDate(today, -1, 'day').valueOf();
      }
    } else {
      model.date = formatTimestamp(weekDateList[weekDateList.length - 1]);
    }
  };

  const { start: startDate, end } = getStartOrEndTimeStamp('week');
  const endDate = addDate(end, -2, 'day').valueOf(); // 限定5天

  const compNumber = ref();
  const getDailyData = async (date: string | Dayjs) => {
    const res = await getDailyDataByDate(formatDate(date));
    if (res.code === ResultCodeEnum.SUCCESS) {
      compNumber.value = res.data * 100;
      console.log('打印***compNumber.value', compNumber.value);
    }
    // if (isNaN(compNumber.value) && useUserStore().isLogined) {
    //   message
    //     .confirm({
    //       msg: '一键订阅未浇水模版消息',
    //       title: '订阅消息'
    //     })
    //     .then(() => {
    //       console.log('点击了确定按钮');
    //       subscribeMsg();
    //     })
    //     .catch(() => {
    //       console.log('点击了取消按钮');
    //     });
    // }
  };

  const handleCalendarChange = (e: { value: string }) => {
    getDailyData(e.value);
  };

  const handleRadioChange = (e: any) => {
    model.value = e.value;
  };

  const form = ref();
  const message = useMessage();
  const { success } = useToast();

  const loading = ref(false);
  const handleSubmit = async () => {
    const { valid } = await form.value.validate();
    if (!valid) return;
    let messageRes: MessageResult | void = undefined;
    if (compNumber.value) {
      messageRes = await message
        .confirm({
          msg: '该日期已完成浇水，确认修改吗？',
          title: '确认修改'
        })
        .catch((err) => {
          console.log('打印***err', err);
        });
    }

    if (!compNumber.value || (messageRes && messageRes.action === 'confirm')) {
      loading.value = true;
      const res = await checkIn({
        date: formatDate(model.date),
        value: Number(model.value) / 100
      });
      if (res.code === ResultCodeEnum.SUCCESS) {
        success({
          msg: '浇水成功'
        });
        init();
      }
      loading.value = false;
    }
  };

  const init = () => {
    showCalendar.value = false;
    getDailyData(formatDate(model.date));
    getData();
    nextTick(() => {
      showCalendar.value = true;
    });
  };

  onMounted(() => {
    initDate();
    init();
  });

  return {
    loading,
    number,
    form,
    compNumber,
    radioList,
    startDate,
    endDate,
    model,
    showCalendar,
    formatter,
    handleRadioChange,
    handleCalendarChange,
    handleSubmit
  };
};
